package com.gemme.gemme.wode;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.gemme.gemme.BaseActivity;
import com.gemme.gemme.MainActivity;
import com.gemme.gemme.R;
import com.gemme.gemme.login.Constant;
import com.gemme.gemme.login.GlideCircleTransform;
import com.gemme.gemme.login.SexAgeActivity;
import com.gemme.gemme.manager.DataManager;
import com.gemme.gemme.util.HttpDrUtil;
import com.gemme.gemme.util.MyOSSUtils;
import com.gemme.gemme.util.PCUtil;
import com.gemme.gemme.util.SPUtil;
import com.gemme.gemme.util.StrUtil;
import com.gemme.gemme.view.Topview;
import com.gemme.gemme.view.TvTvArrow;
import com.google.android.material.tabs.TabLayout;
import com.jaeger.library.StatusBarUtil;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.listener.OnResultCallbackListener;
import com.yanzhenjie.recyclerview.SwipeRecyclerView;

import org.jsoup.helper.DataUtil;

import java.io.File;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

//侧滑删除地址
public class WoAccountActivity extends BaseActivity implements View.OnClickListener {
    public static final int type_nicheng = 1;
    public static final int type_sex_birthday= 2;
    public static final int type_qianming= 3;
    public static final int type_anquanlingpai= 4;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account_wo);
        initTop();
        initView();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getData();
            }
        }).start();

    }
    TvTvArrow tta_nicheng;
    TvTvArrow tta_sex;
    TvTvArrow tta_qianming;
    TvTvArrow tta_birthday;
    TvTvArrow tta_aqlp;
    RelativeLayout rl_touxiang;
    ImageView iv_head;
    private void initView() {
        tta_nicheng = findViewById(R.id.tta_nicheng);
        tta_sex = findViewById(R.id.tta_sex);
        tta_qianming = findViewById(R.id.tta_qianming);
        tta_birthday = findViewById(R.id.tta_birthday);
        tta_aqlp = findViewById(R.id.tta_aqlp);
        rl_touxiang = findViewById(R.id.rl_touxiang);

        iv_head = findViewById(R.id.iv_head);
        tta_nicheng.setLeftText("昵称").setRightText("").setArrowVisble(true);
        tta_sex.setLeftText("性别").setRightText("").setArrowVisble(true);
        tta_qianming.setLeftText("签名").setRightText("").setArrowVisble(true);
        tta_birthday.setLeftText("出生日期").setRightText("").setArrowVisble(true);
        tta_aqlp.setLeftText("安全令牌").setRightText("修改").setArrowVisble(true);
        tta_nicheng.setOnClickListener(this);
        tta_sex.setOnClickListener(this);
        tta_qianming.setOnClickListener(this);
        tta_birthday.setOnClickListener(this);

        tta_aqlp.setOnClickListener(this);


        rl_touxiang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PCUtil.selectPic(mContext,1,onResultCallbackListener);
            }
        });

    }




    @Override
    protected void onResume() {
        super.onResume();



    }

    private void initTop() {
//        StatusBarUtil.setColor(this,getResources().getColor(R.color.white_color) );
        StatusBarUtil.setTransparent(this);
//        StatusBarUtil.setTranslucent(this,250);
        Topview topview = findViewById(R.id.topview);
        topview.setContentText("我的账号");
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tta_nicheng:
                Intent intent = new Intent(mContext, NIchengActivity.class);
                intent.putExtra("data",tta_nicheng.getRightText());
                startActivityForResult(intent,type_nicheng);
                break;

            case R.id.tta_sex:
                Intent intent1 = new Intent(mContext, SexAgeActivity.class);
                intent1.putExtra("data",1000);
                startActivityForResult(intent1,type_sex_birthday);
                break;

            case R.id.tta_qianming:
                Intent intent2 = new Intent(mContext, QianMingActivity.class);
                intent2.putExtra("data",tta_qianming.getRightText());
                startActivityForResult(intent2,type_qianming);
                break;

            case R.id.tta_birthday:
                //去掉出生日期修改
                /*Intent intent3 = new Intent(mContext, SexAgeActivity.class);
                startActivityForResult(intent3,type_sex_birthday);*/
                Toast.makeText(mContext, "出生日期不可修改", Toast.LENGTH_SHORT).show();
                break;

            case R.id.tta_aqlp:
                Intent intent4 = new Intent(mContext, AnquanLingpaiActivity.class);
                startActivityForResult(intent4,type_anquanlingpai);
                break;
        }
    }


    private void getData() {
        DataManager.refreshToken(mContext);
//        todo 需要刷新token
//        http://192.168.1.7:9999/user/userapp/getuserinfo
        Uri.Builder builder = Uri.parse(DataManager.BaseUrl + "user/userapp/getuserinfo").buildUpon();
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
//        headMap.put(DataManager.AuthorizationKey,"Bearer 2af9350c-dad4-4e04-b5b9-6a931f9b7b0c");
        DataManager.toServer3(mContext, builder.toString(), DataManager.GET_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                /*tv_name
                        iv_head*/
                try{
                    System.out.println();
                    WodeInfoBean wodeInfoBean = JSON.parseObject(response, WodeInfoBean.class);
                    Object nickname = wodeInfoBean.getData().getNickname();
                    Object signature = wodeInfoBean.getData().getSignature();
                    tta_nicheng.setRightText(StrUtil.noNUll(nickname));
                    tta_qianming.setRightText(StrUtil.noNUll(signature));
                    tta_sex.setRightText(StrUtil.noNUll(wodeInfoBean.getData().getSex()).equals("1") ? "男" : "女");
                    tta_birthday.setRightText(StrUtil.noNUll(wodeInfoBean.getData().getBirthday()));
//                    tv_name.setText(StrUtil.noNUll(nickname));
                    Object headImgUrl = wodeInfoBean.getData().getHeadImgUrl();
                    Glide.with(mContext).load(StrUtil.noNUll(headImgUrl)).transform(new GlideCircleTransform(mContext))
                            .into(iv_head);
                }catch (Exception e){

                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            if(requestCode == type_nicheng || requestCode == type_qianming || requestCode == type_anquanlingpai){
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        getData();
                    }
                }).start();
            }

            if(requestCode == type_sex_birthday){//更新了性别和出生日期

                updateToServer();
            }
        }catch (Exception e){

        }
    }

    private void updateToServer() {
        String user_sex = SPUtil.getDataForString(this, Constant.user_sex, Constant.type_qiyong);
//        String user_birthDay = SPUtil.getDataForString(this, Constant.user_birthDay, Constant.type_qiyong);

        HashMap<String, Object> ulrMap = new HashMap<>();
//        if(!TextUtils.isEmpty(user_birthDay) && !Constant.type_qiyong.equals(user_birthDay))
//            ulrMap.put("birthday", user_birthDay);
        if(!TextUtils.isEmpty(user_sex) && !Constant.type_qiyong.equals(user_sex)){
            Integer sex_int = user_sex == "男"? 1 : 2;
            ulrMap.put("sex", sex_int);
        }


        String url = DataManager.BaseUrl + "user/userapp/edituser?";
        url = url + HttpDrUtil.addUrl(ulrMap);
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
//        headMap.put(DataManager.AuthorizationKey,"Bearer 2af9350c-dad4-4e04-b5b9-6a931f9b7b0c");
        DataManager.toServer3(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    System.out.println();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            getData();
                        }
                    }).start();

                }catch (Exception e){

                }
            }
        });
    }


    String headPath;

    OnResultCallbackListener onResultCallbackListener = new OnResultCallbackListener(){

        @Override
        public void onResult(List result) {
            System.out.println("");

            try {
                headPath = ((LocalMedia) result.get(0)).getCompressPath();
                Glide.with(mContext).load(headPath).transform(new GlideCircleTransform(mContext))
                        .into(iv_head);
                submitHeadPicture();
            }catch (Exception e){

            }
//            submitHeadPicture();





        }

        @Override
        public void onCancel() {
            System.out.println("");
        }
    };


    String http_head_url;

    private void submitHeadPicture() {
        long l = System.currentTimeMillis();
        String mPicturePath = headPath;
        if (!TextUtils.isEmpty(mPicturePath) && (new File(mPicturePath).exists())){
//            String objectName =  new File(mPicturePath).getName().replace(".",l+".");
            String objectName =  new File(mPicturePath).getName().replace(".",l+".");
            objectName = MyOSSUtils.getFileName(objectName, 2, 0);
            MyOSSUtils.getInstance().upImage(mContext, new MyOSSUtils.OssUpCallback() {
                @Override
                public void successImg(String img_url) {

                    http_head_url = img_url;
                    System.out.println("");
                    toServerPicture();
                }

                @Override
                public void successVideo(String video_url) {
                    System.out.println("");
                }

                @Override
                public void inProgress(long progress, long zong) {
                    System.out.println("");
                }
            }, objectName, mPicturePath);
        }else{//没有图片地址直接上传
        }

    }

    private void toServerPicture() {
        if(TextUtils.isEmpty(http_head_url))
            return;
        String url = DataManager.BaseUrl + "user/userapp/edituser?" +
                "headImgUrl="+http_head_url;
        HashMap<String, String> headMap = new HashMap<>();
        headMap.put(DataManager.AuthorizationKey,DataManager.getToken(mContext));
//        headMap.put(DataManager.AuthorizationKey,"Bearer 2af9350c-dad4-4e04-b5b9-6a931f9b7b0c");
        DataManager.toServer3(mContext, url, DataManager.POST_TYPE, "", headMap, new DataManager.GeResponse() {
            @Override
            public void onResponse(String response) {
                try{
                    System.out.println();

                }catch (Exception e){

                }
            }
        });
    }


}